package com.bigShen.pattern.template;

import org.springframework.jdbc.core.RowMapper;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: lei.shen
 * @date: 2018/10/5
 */
public class JDBCTemplate {

    DataSource dataSource;

    public JDBCTemplate(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    public List<?> executeQuery(String sql, RowMapper<?> rowMapper, Object[] values) {

        Connection con = null;
        PreparedStatement statement = null;
        ResultSet rs = null;
        try {

            // 1.加载驱动

            // 2.建立连接
            con = this.dataSource.getConnection();

            // 3.创建语句集
            statement = con.prepareStatement(sql);

            // 4.执行语句集,获得结果集
            rs = statement.executeQuery();

            // 5.解析语句集
            List<Object> result = new ArrayList<Object>();
            int rowNum = 1;
            while (rs.next()) {
                result.add(rowMapper.mapRow(rs, rowNum));
            }
            return  result;
        } catch (Exception e) {
           e.printStackTrace();
        } finally {
            // 6.关闭结果集
            try {
                rs.close();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }

            // 7.关闭语句集
            try {
                statement.close();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            // 8.关闭连接
            //通常把它放到连接池回收
        }
        return null;
    }

}
